/*
 * 文件名：SuperBudgetOfgroupController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年5月11日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.fia.web;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.domain.ProBudgetOfgroupDomain;
import top.infopub.mgr.fia.service.ProBudgetOfgroupService;
import top.infopub.mgr.fia.service.SuperBudgetOfgroupService;
import top.infopub.mgr.fia.vo.ProBudgetOfgroupVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.PreProjectService;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.fia.ProBudgetOfgroup;
import top.infopub.model.fia.ProBudgetOfgroupDtl;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.PreProject;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 项目公司年度控股指标预算
 * @author wuzhiyang
 * @version 2020年5月11日
 * @see ProBudgetOfgroupController
 * @since
 */
@Controller
@RequestMapping("/proBudgetOfgroup")
public class ProBudgetOfgroupController extends GenericFlowController {

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private SuperBudgetOfgroupService superBudgetOfgroupService;

    @Autowired
    private ProBudgetOfgroupService proBudgetOfgroupService;

    @Autowired
    private PreProjectService preProjectService;

    /**
     * 项目公司年度控股指标预算
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        request.setAttribute("bindOrgId", bindOrgId);
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            orgInfos = orgInfoService.selectByProCodeIsnOtNull();
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIdsAndProCodeIsnOtNull(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "fia/lay-proBudgetOfgroup-list";
    }

    /**
     * 项目公司年度控股指标预算
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProBudgetOfgroupDomain> queryDataByCondition(ProBudgetOfgroupVo proBudgetOfgroupVo,
                                                              ParamPage paramPage) {
        Page<ProBudgetOfgroupDomain> page = new Page<ProBudgetOfgroupDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        // 默认查询
        /*if (StringUtils.isEmpty(proBudgetOfgroupVo.getHrOrgBillId())) {
            proBudgetOfgroupVo.setHrOrgBillId((String)SessionUserUtils.getSessionAttribute("bindOrgId"));
        }*/
        //查询时，结束日期增加一天
        if (proBudgetOfgroupVo.getEndDate() != null) {
            proBudgetOfgroupVo.setEndDate(DateUtils.addDays(proBudgetOfgroupVo.getEndDate(), 1));
        }
        page = proBudgetOfgroupService.selectByDomainWhere(page, proBudgetOfgroupVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 项目公司年度控股指标预算-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            orgInfos = orgInfoService.selectByProCodeIsnOtNull();
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIdsAndProCodeIsnOtNull(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        OrgInfo info = orgInfoService.selectByPrimaryKey((String)SessionUserUtils.getSessionAttribute("bindOrgId"));
        if (info != null) {
            request.setAttribute("orgTypes", info.getTypes());
            request.setAttribute("billOrgName", info.getCompName());
        }
        return "fia/lay-proBudgetOfgroup-add";
    }

    /**
     * 根据id查询项目公司年度控股指标预算详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 项目公司年度控股指标预算Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        ProBudgetOfgroupVo proBudgetOfgroupVo = proBudgetOfgroupService.queryById(id);
        map.put("proBudgetOfgroupVo", proBudgetOfgroupVo);
        return new ModelAndView("fia/lay-proBudgetOfgroup-detail", map);
    }

    /**
     * 新增项目公司年度控股指标预算
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,
                                    ProBudgetOfgroupVo proBudgetOfgroupVo) {

        String proCodeAndCodes = request.getParameter("proCodeAndCodes");
        String[] split = proCodeAndCodes.split("\\_");
        if (StringUtils.isBlank(proBudgetOfgroupVo.getId())) {
            int count = proBudgetOfgroupService.count(proBudgetOfgroupVo.getBelongsYear(),
                split[1]);
            //判断是否存在同一公司名称、同一预算年度已有生效中单据
            if (count > 0) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("已有同一公司同一预算年度单据，不可重复提交");
            }
        }

        String[] monthDtl = request.getParameterValues("months");//子项月份
        String[] investFeeDtl = request.getParameterValues("investFee");//子项-投资额
        String[] finFeeDtl = request.getParameterValues("finFee");//子项-融资额
        String[] manageProfitDtl = request.getParameterValues("manageProfit");//子项-管理净利润

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
         * 项目公司年度控股指标预算主表处理
         */
        String hrStaffApplyid = request.getParameter("hrStaffApplyid");
        String staffname = request.getParameter("staffname");
        String hrOrgid = request.getParameter("hrOrgid");
        String hrDeptid = request.getParameter("hrDeptid");
        String proCode = split[0];
        proBudgetOfgroupVo.setProCode(proCode);
        //获取项目名称
        List<PreProject> byProCode = preProjectService.selectByProCode(proCode);
        if (CollectionUtils.isNotEmpty(byProCode)) {
            PreProject preProject = byProCode.get(0);
//            proBudgetOfgroupVo.setProName(preProject.getProName());
        }
        proBudgetOfgroupVo.setHrOrgBillId(split[1]);
        proBudgetOfgroupVo.setHrDeptId(hrDeptid);
        proBudgetOfgroupVo.setHrOrgId(hrOrgid);
        proBudgetOfgroupVo.setStaffName(staffname);
        proBudgetOfgroupVo.setHrStaffApplyId(hrStaffApplyid);
        String id = IdFactory.getUUIDUpper();
        proBudgetOfgroupVo.setId(id);
        proBudgetOfgroupVo.setHrStaffApplyId(vo.getHrStaffId());
        proBudgetOfgroupVo.setAddBy(vo.getId());
        proBudgetOfgroupVo.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("fia_pro_budget_ofgroup");
        proBudgetOfgroupVo.setCodes(codes);
        proBudgetOfgroupVo.setProcessStatus("9");//生效中
        proBudgetOfgroupVo.setUptBy(vo.getId());
        proBudgetOfgroupVo.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //子项处理
        List<ProBudgetOfgroupDtl> proBudgetOfgroupDtls = new ArrayList<>();
        for (int i = 0; i < monthDtl.length; i++ ) {
            String months = monthDtl[i];
            ProBudgetOfgroupDtl proBudgetOfgroupDtl = new ProBudgetOfgroupDtl();
            String subId = IdFactory.getUUIDUpper();//自动生成主键
            proBudgetOfgroupDtl.setId(subId);
            proBudgetOfgroupDtl.setProBudgetId(id);
            proBudgetOfgroupDtl.setMonths(Integer.parseInt(months));
            proBudgetOfgroupDtl.setManageProfit(new BigDecimal(manageProfitDtl[i]));
            proBudgetOfgroupDtl.setFinFee(new BigDecimal(finFeeDtl[i]));
            proBudgetOfgroupDtl.setInvestFee(new BigDecimal(investFeeDtl[i]));
            proBudgetOfgroupDtl.setAddBy(vo.getId());
            proBudgetOfgroupDtl.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            proBudgetOfgroupDtls.add(proBudgetOfgroupDtl);
        }

        proBudgetOfgroupService.saveProBudgetOfgroup(proBudgetOfgroupVo, proBudgetOfgroupDtls);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "新增建投总部年度控股指标预算 ：公司名=" + proBudgetOfgroupVo.getOrgProName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 修改 项目公司年度控股指标预算状态
     * @param
     * @return
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(String id) {
        ProBudgetOfgroup proBudgetOfgroup = proBudgetOfgroupService.selectByPrimaryKey(id);
        String oldStatus = proBudgetOfgroup.getProcessStatus();
        String newStatus = "9";
        if ("9".equals(oldStatus)) {
            newStatus = "10";
        }
        else {
            newStatus = "9";
        }
        proBudgetOfgroup.setProcessStatus(newStatus);
        proBudgetOfgroup.setUptTime(new Date());
        proBudgetOfgroup.setUptBy(SessionUserUtils.getSessionUserId());
        proBudgetOfgroupService.updateBySelective(proBudgetOfgroup);
        // 操作日志
        LogUtil.bizLog(LogUtil.LogModelType.OTHER, LogUtil.AcctionType.UPDATE,
            "修改状态   项目公司年度控股指标预算表单据ID:" + proBudgetOfgroup.getCodes(), "");
        return RspVo.getSuccessResponse();
    }

}
